// pages/login/login.ts
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 登录
    const that = this
    wx.login({
      success: async (res) => {
        wx.request({
          url: `https://www.liqiantw.icu:3000/server/${res.code}`,
          method: 'GET',
          success: (res: any) => {
            const { openid, token, nickName, avatar } = res.data
            app.globalData.userInfo = {
              openid,
              token,
              nickName: nickName || '',
              avatarUrl: avatar || ''
            }
            that.saveScoreToServer(openid)
          },
          fail: (err => {
            console.log(err);
            wx.navigateTo({ url: '../math/math' })
          })
        })
      },
    })
  },
  async saveScoreToServer(name: string) {
    const scores = wx.getStorageSync('scores') || []
    if (scores.length) {
      const mid = scores.map(({ dateTime, scoreTime, allTest, allRight, type }: any) => ({
        date: new Date(dateTime).getTime(),
        name,
        rightNum: allRight,
        testMinute: scoreTime,
        totalNum: allTest,
        type
      }))
      wx.request({
        url: `https://www.liqiantw.icu:3000/score/batchAdd`,
        method: 'POST',
        data:mid,
        header: {
          Authorization: app.globalData.userInfo.token
        },
        success: () => {
          wx.removeStorageSync('scores')
          wx.navigateTo({ url: '../math/math' })
        },
        fail: (err => {
          console.log(err);
          wx.navigateTo({ url: '../math/math' })
        })
      })
    } else {
      wx.switchTab({ url: '../math/math' })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  }
})